<?php

namespace common\models\user;

use Yii;
use common\helpers\ArrayHelper;
use common\helpers\StringHelper;
use common\helpers\Url;
use common\helpers\DateHelper;
use common\models\trend\TrendLevel;

/**
 * This is the model class for table "{{%user_meta}}".
 *
 * @property int $id
 * @property string $nickname
 * @property string $mobile
 * @property string $avatar
 * @property string $cover
 * @property int $gender
 * @property string $signature
 * @property string $birthday
 * @property string $location
 * @property int $ip
 * @property int $created_at
 * @property int $updated_at
 */
class UserMeta extends \common\db\ActiveRecord {

    public $autoPushOssUpload = true;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%user_meta}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['id'], 'required'],
            [['id', 'gender', 'ip', 'created_at', 'updated_at'], 'integer'],
            [['birthday'], 'safe'],
            [['nickname'], 'string', 'max' => 32],
            [['mobile', 'avatar', 'cover'], 'string', 'max' => 255],
            [['signature'], 'string', 'max' => 128],
            [['location'], 'string', 'max' => 64],
            [['id'], 'unique'],
            [['nickname'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'nickname' => '昵称',
            'mobile' => '手机号',
            'avatar' => '头像',
            'cover' => '空间封面',
            'gender' => '性别',
            'signature' => '个人签名',
            'birthday' => '出生日期',
            'location' => '位置',
            'ip' => 'IP',
            'created_at' => '注册时间',
            'updated_at' => '最后修改时间',
        ];
    }

    /**
     * 关联账号信息
     */
    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'id']);
    }

    /**
     * 关联认证信息
     */
    public function getAuthent() {
        return $this->hasOne(UserAuthent::className(), ['user_id' => 'id']);
    }

    /**
     * 关联认证信息
     */
    public function getCertified() {
        return $this->getAuthent()->andWhere([
            'status' => UserAuthent::STATUS_ACTIVE
        ])->exists();
    }

    /**
     * 用户行为动态
     */
    public function getTrend() {
        return $this->hasOne(UserTrend::className(), ['id' => 'id']);
    }

    /**
     * 个人主页封面
     */
    public function getCovers() {
        return [];
//        return $this->hasMany(UserGallery::className(), ['user_id' => 'id'])->orderBy(['listorder' => SORT_ASC]);
    }

    /**
     * 关联用户关注的人
     */
    public function getFollows() {
        return $this->hasMany(UserRelation::className(), ['user_id' => 'id']);
    }

    /**
     * 关联用户粉丝
     */
    public function getFans() {
        return $this->hasMany(UserRelation::className(), ['to_user_id' => 'id']);
    }

    /**
     * 当前用户是否已关注某人
     */
    public function getFollowed() {
        return $this->hasOne(UserRelation::className(), ['to_user_id' => 'id'])->andWhere([
            'user_id' => Yii::$app->user->id
        ])->exists();
    }

    /**
     * 获取用户名信息
     */
    public function getUsername() {
        if ($this->nickname) {
            return $this->nickname;
        }
        return $this->user ? $this->user->username : '--';
    }

    /**
     * 关联用户标签
     */
    public function getOwnTag() {
        return $this->hasMany(UserTag::className(), ['user_id' => 'id']);
    }

    /**
     * 用户标签
     */
    public function getTrendTags() {
        return $this->hasMany(\common\models\trend\TrendTag::className(), ['id' => 'tag_id'])
        ->via('ownTag');
    }

    /**
     * 用户标签
     */
    public function getAccounts() {
        return $this->hasMany(UserAccount::className(), ['user_id' => 'id']);
    }

    /**
     * 获取用户标签
     */
    public function getTags() {
        return ArrayHelper::getColumn($this->trendTags, 'name');
    }

    /**
     * 是否VIP用户
     */
    public function getVip() {
        return true;
    }

    /**
     * 是否会员卡用户
     */
    public function getCard() {
        return $this->hasOne(UserCard::className(), ['user_id' => 'id']);
    }

    /**
     * 是否球迷会用户
     */
    public function getFanasocMember() {
        return $this->hasOne(\common\models\fanasoc\FanasocMember::className(), ['user_id' => 'id']);
    }

    /**
     * 是否球迷会用户
     */
    public function getFanasoc() {
        return $this->hasOne(\common\models\fanasoc\Fanasoc::className(), ['id' => 'fanasoc_id', 'round_id' => 'round_id'])
        ->via('fanasocMember');
    }

    /**
     * 是否年票用户
     */
    public function getAnnual() {
        return $this->hasOne(UserAnnual::className(), ['user_id' => 'id']);
    }

    /**
     * 用户等级
     */
    public function getLevel() {
        $lid = $this->trend ? $this->trend->level_id : 0;
        if (!$lid) {
            $lid = 1;
        }
        $level = TrendLevel::findOne($lid);
        if ($level) {
            return $level;
        }
        return [
            'label' => '1',
            'text' => '小白',
            'need' => 100,
        ];
    }

    /**
     * 用户等级
     */
    public function getLikes() {
        return 1;
    }

    /**
     * 获取关注、粉丝数
     */
    public function getRelations() {
        return [
            'follows' => $this->getFollows()->count(),
            'fans' => $this->getFans()->count(),
        ];
    }

    /**
     * 用户账户数据
     */
    public function getAccount() {
        $account = [
            'follows' => (int) $this->getFollows()->count(),
            'fans' => (int) $this->getFans()->count(),
            'gold' => 0,
            'credit' => 0,
            'experience' => 0,
            'likes' => 0,
        ];
        $trend = $this->trend;
        if (!$trend) {
            $trend = UserTrend::createAccount($this->id);
        }
        if ($trend) {
            $account['gold'] = $trend->gold;
            $account['credit'] = $trend->credit;
            $account['experience'] = $trend->experience;
            $account['likes'] = $trend->likes;
        }
        return $account;
    }

    /**
     * 获取生日资料数据
     */
    public function getBirth() {
        if (!$this->birthday) {
            return null;
        }
        return DateHelper::birthday($this->birthday);
    }

    /**
     * 获取用户头像
     * @return 
     */
    public function getPortrait() {
        $avatar = $this->setAvatar();
        return Url::attach($avatar);
    }

    /**
     * 过滤手机号敏感字段
     * @inheritdoc
     */
    public function decryptMobile($mask = true) {
        $mobile = Yii::$app->security->decryptMaster($this->mobile);
        if ($mask !== false) {
            return StringHelper::maskChar($mobile, 3, 2);
        }
        return $mobile;
    }

    /**
     * @inheritdoc
     */
    public function setMobile($mobile) {
        if ($mobile) {
            /* @var $security \common\base\Security */
            $security = Yii::$app->security;
            $this->mobile = $security->encryptMaster($mobile);
        }
    }

    /**
     * @inheritdoc
     */
    public function setAvatar($avatar = null) {
        if ($avatar === null) {
            $avatar = ArrayHelper::getValue(Yii::$app->params, 'defaultImages.user_avatar');
            $this->autoPushOssUpload = false;
        }
        return $this->avatar = $avatar;
    }

    /**
     * @inheritdoc
     */
    public function setUniqueNickname($nickname = null) {
        if ($nickname) {
            $rand = '';
            do {
                $exists = static::find()->where(['nickname' => $nickname . $rand])->exists();
                if ($exists) {
                    $rand = Url::toShort(microtime(true));
                }
            } while ($exists);
            $this->nickname = $nickname . $rand;
        }
    }

    /**
     * 融云TOKEN
     * @return 
     */
    public function getImToken() {
        return $this->hasOne(UserIm::className(), ['user_id' => 'id'])->andWhere([
            'or',
            ['expired_at' => 0],
            ['>', 'expired_at', time()]
        ]);
    }

    /**
     * 融云TOKEN
     */
    public function getRongCloudToken() {
        if ($this->imToken) {
            return $this->imToken->getToken('');
        }
        return UserIm::findOrRegister($this->id);
    }

    /**
     * @inheritdoc
     */
    public function afterFind() {
        if (!$this->avatar) {
            $this->setAvatar();
            $this->save(false);
        }
        parent::afterFind();
    }

    /**
     * @inheritdoc
     */
    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        $avatar = ArrayHelper::getValue($changedAttributes, 'avatar');
        if ($avatar !== null && $this->autoPushOssUpload != false) {
            Yii::$app->alioss->putObjectACL(ltrim($this->avatar, '/'), 'public-read');
        }
    }

}
